package localizer.main;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class ContactPicker extends Activity implements OnClickListener{

	BroadcastReceiver br1;
	String tipePicker;
	
	private static final int CONTACT_PICKER_RESULT = 1001; 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		TextView title = (TextView)findViewById(R.id.contactTitle);
		tipePicker = getIntent().getExtras().getString("tipe");
		if(tipePicker.equals("silent")){
			title.setText(R.string.silentAlert);
		} else if(tipePicker.equals("loc")){
			title.setText(R.string.loc);
		} else {
			title.setText(R.string.alert);
		}
		
		((Button)findViewById(R.id.contact_browser)).setOnClickListener(this);
		((Button)findViewById(R.id.contact_ok)).setOnClickListener(this);
		br1 = new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        
	}
	
	protected void onResume(){
		super.onResume();
		((ProgressBar)findViewById(R.id.contact_pbar)).setVisibility(ProgressBar.GONE);
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.contact_browser){
			Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,  
					            Contacts.CONTENT_URI);  
			startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);  

		}
		if(v.getId() == R.id.contact_ok){
			if( !((EditText)findViewById(R.id.contact_phone)).getText().toString().equals("")){
				SmsManager sms = SmsManager.getDefault();
				String mtext = ((EditText) findViewById(R.id.contact_login)).getText().toString() + " " + ((EditText) findViewById(R.id.contact_pwd)).getText().toString();
				
				if(tipePicker.equals("silent")){
					tipePicker = "ring silent"; 
				} else if(tipePicker.equals("loc")){
					tipePicker += " " + SmsReceiver.ID_LOC;
				}
				mtext += " " + tipePicker;
				
				
				String SENT = "SMS_SENT";
		        String DELIVERED = "SMS_DELIVERED";
		 
		        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
		            new Intent(SENT), 0);
		 
		        //---when the SMS has been sent---
		        registerReceiver(br1, new IntentFilter(SENT));
		 
		        sms.sendTextMessage(((EditText)findViewById(R.id.contact_phone)).getText().toString(), null, mtext, sentPI, null);
				sms = null;
				
				finish();
			}
		}
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		try{
			unregisterReceiver(br1);
		}catch (Exception e){}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        switch (requestCode) {
	        case CONTACT_PICKER_RESULT:
	            Cursor cursor = null;
	            String email = "";
	            try {
	                Uri result = data.getData();;

	                // get the contact id from the Uri
	                String id = result.getLastPathSegment();

	                // query for everything email
	                cursor = getContentResolver().query(Phone.CONTENT_URI,
	                        null, Phone.CONTACT_ID + "=?", new String[] { id },
	                        null);

	                int emailIdx = cursor.getColumnIndex(Phone.DATA);

	                // let's just get the first email
	                if (cursor.moveToFirst()) {
	                    email = cursor.getString(emailIdx);
	                    Log.v("numero", "Got email: " + email);
	                } else {
	                    Log.w("algoerrado", "No results");
	                }
	            } catch (Exception e) {
	                Log.e("contato ","Failed to get email data", e);
	            } finally {
	                if (cursor != null) {
	                    cursor.close();
	                }
	                EditText emailEntry = (EditText) findViewById(R.id.contact_phone);
	                emailEntry.setText(email);
	                if (email.length() == 0) {
	                    Toast.makeText(this, "No Phone-number found for contact.",
	                            Toast.LENGTH_LONG).show();
	                }

	            }

	            break;
	        }

	    } else {
	        Log.w("contato", "Warning: activity result not ok");
	    }
	}


}
